package com.my.demo.shiro.realms;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.my.demo.pojo.User;
import com.my.demo.service.EnterpriseUserService;
import com.my.demo.service.PermissonService;
import com.my.demo.service.UserService;
import com.my.demo.shiro.token.JwtToken;
import org.apache.shiro.authc.AccountException;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * @author liangyuanshao
 * @date 2021/12/18 - 19:31
 */
public class CustomerRealm extends AuthorizingRealm {

  @Autowired
  UserService userService;
  @Autowired
  PermissonService permissonService;
  @Autowired
  EnterpriseUserService enterpriseUserService;

  @Override
  public boolean supports(AuthenticationToken token) {
    return token instanceof JwtToken;
  }

  @Override
  protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
    System.out.println("进入授权");
    String userName= (String) principals.getPrimaryPrincipal();
    Integer userId = userService.selectIdByName(userName);
    Integer spaceNo = permissonService.getById(userId).getSpaceNo();
    Integer type = enterpriseUserService.getType(spaceNo,userId);
    SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
    if(type<=1){
      simpleAuthorizationInfo.addRole("creater");
      System.out.println(userName+"权限为:creater");
    }
    if(type<=2){
      simpleAuthorizationInfo.addRole("administrator");
      System.out.println(userName+"权限为:administrator");

    }
    if(type<=3){
      simpleAuthorizationInfo.addRole("user");
      System.out.println(userName+"权限为:user");

    }
    return simpleAuthorizationInfo;
  }

  @Override
  protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authcToken)
      throws AuthenticationException {

    JwtToken jwtToken = (JwtToken) authcToken;
    if (jwtToken.getPrincipal() == null) {
      throw new AccountException("JWT token参数异常！");
    }
    // 从 JwtToken 中获取当前用户
    String userName = jwtToken.getPrincipal().toString();
    System.out.println("getCredentials()"+authcToken.getCredentials());

    //从数据库获得的 用户名，密码
    QueryWrapper<User> wrapper = new QueryWrapper<>();
    wrapper.eq("user_name", userName);
    User user = userService.getOne(wrapper);

    if(user!=null){
      //返回数据库信息
      SimpleAuthenticationInfo simpleAuthenticationInfo = new SimpleAuthenticationInfo(user.getUserName(), user.getPassword(),this.getName());
      return simpleAuthenticationInfo;
    }


    return null;
  }

}
